﻿
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Admin.Common;
using Zocono.WCS.Admin.Models.Module;
using Zocono.WCS.Admin.Models.User;
using Zocono.WCS.Application.AppTraces;
using Zocono.WCS.Application.AppUserManage;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Infrastructure.ApllicationDto.DtoUser;

namespace Zocono.WCS.Admin.Controllers
{
    [BasicAuth]
    public class AdminController : BaseController
    {
        private readonly UserApp _userApp;

        public AdminController(UserApp userApp, IMemoryCache memoryCache, TracesApp tracesApp, IHttpContextAccessor httpContextAccessor) : base(memoryCache, tracesApp, httpContextAccessor)
        {
            _userApp = userApp;
        }

        /// <summary>
        /// 角色管理
        /// </summary>
        /// <returns></returns>
        public ActionResult Role()
        {
            //await AddTracesInfo();
            return View();
        }
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> RoleList()
        {
            var list = await _userApp.GetRoleInfoAsync();
            var PageData = new TableData<RoleInfoDto>(Draw, list.Count, list.Count, list);
            //await AddTracesInfo(5, 0, "获取角色列表");
            return Json(PageData);
        }
        /// <summary>
        /// 添加角色
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> RoleAdd(long id)
        {
            var info = new RoleInfoDto();
            if (id != 0)
                info = await _userApp.GetRoleInfoByIdAsync(id);
            //await AddTracesInfo(5, 0, "获取角色信息");
            return View(info);
        }

        public async Task<ActionResult> RoleFunctionAdd(long id)
        {
            ViewData["id"] = id;
            var list = await _userApp.GetFunctionInfoAsync();//获取所有菜单
            var roleFunctionList = new List<RoleFunctionPage>();
            var pList = new List<ModulePage>();
            if (id > 0)
                roleFunctionList = await _userApp.GetRoleFunctionByRoleId(id);
            ModulePage module;
            Children children;
            foreach (var info in list) //处理菜单信息
            {
                if (info.Status == 1 && info.Pid == 0)
                {
                    module = new ModulePage();
                    module.id = info.ID.ToString();
                    module.name = info.FullName;
                    module.@checked = roleFunctionList.Find(e => e.FunctionID == info.ID) == null ? false : true;
                    pList.Add(module);
                }
                if (info.Status == 1 && info.Pid > 0)
                {
                    module = pList.Find(i => i.id.ToInt64() == info.Pid);
                    if (module != null)
                    {
                        if (module.children == null)
                            module.children = new List<Children>();
                        children = new Children();
                        children.id = info.ID.ToString();
                        children.name = info.FullName;
                        children.@checked = roleFunctionList.Find(e => e.FunctionID == info.ID) == null ? false : true;
                        module.children.Add(children);
                    }
                }
            }
            //await AddTracesInfo(5, 0, "获取角色权限信息");
            return View(pList);
        }


        public async Task<JsonResult> OperateRole()
        {
            var dto = new RoleInfoDto();
            dto.ID = Request.Form["id"].ToInt64();
            dto.Code = Request.Form["code"].ToString();
            dto.FullName = Request.Form["fullName"].ToString();
            dto.Description = Request.Form["des"].ToString();
            dto.UpdateTime = DateTime.Now;
            bool result;
            string msg;
            try
            {
                if (dto.ID == 0)
                {
                    result = await _userApp.addRoleAsync(dto);
                    await AddTracesInfo(2, 0, "新增角色信息");
                }
                else
                    result = await _userApp.UpdateRoleByIdAsync(dto);
                await AddTracesInfo(2, 0, "修改角色信息");
                msg = result ? "成功" : "失败";
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }
            return CreateJsonGetResult(result, msg);
        }

        public async Task<JsonResult> DelRoleById()
        {
            var id = Request.Form["id"].ToInt64();
            bool result;
            string msg;
            try
            {
                result = await _userApp.DelRoleByIdAsync(id);
                msg = result ? "成功" : "失败";
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }

            await AddTracesInfo(4, 0, "删除角色信息");
            return CreateJsonGetResult(result, msg);

        }


        /// <summary>
        /// 设置菜单权限
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> SetRoleFunction()
        {
            var id = Request.Form["id"].ToInt64();
            if (id <= 0)
                return CreateJsonGetResult(false, "保存错误，请刷新页面！");

            var list = new List<RoleFunctionInfoDto>();
            RoleFunctionInfoDto dto;
            foreach (var i in Request.Form.Keys)
            {
                if (i.Contains("role"))
                {
                    dto = new RoleFunctionInfoDto();
                    dto.RoleID = id;
                    dto.FunctionID = Request.Form[i].ToInt64();
                    dto.ParentID = 0;
                    dto.TreeIndex = 0;
                    dto.TreeIndex = 0;
                    dto.Operation = 0;
                    list.Add(dto);
                }
            }
            bool result;
            string msg;
            try
            {
                result = await _userApp.UpdateRoleFunctionInfoByRoleIdAsync(list);
                msg = result ? "成功" : "失败";
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }
            await AddTracesInfo(3, 0, "设置角色信息权限");
            return CreateJsonGetResult(result, msg);
        }

        /// <summary>
        /// 菜单管理
        /// </summary>
        /// <returns></returns>
        public async Task<ActionResult> Function()
        {
            //await AddTracesInfo();
            return View();
        }
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> FunctionList()
        {
            var functionInfoDto = new FunctionInfoDto();

            functionInfoDto.ParentMenus = new List<ParentMenu>();
            functionInfoDto.FullName = Request.Form["fullName"].ToString();
            functionInfoDto.URL = Request.Form["url"].ToString();
            functionInfoDto.Status = Request.Form["status"].ToInt32();
            var list = await _userApp.GetFunctionInfoAsync(functionInfoDto);
            var listgroupby = list.Distinct().ToList();
            foreach (var item in listgroupby)
            {
                functionInfoDto.ParentMenus.Add(new ParentMenu { Pid = item.ID, PidName = item.FullName });
            }
            //foreach (var item in list)
            //{
            //    item.ParentMenus = functionInfoDto.ParentMenus;
            //}
            list.ForEach(l => l.ParentMenus = functionInfoDto.ParentMenus);
            var PageData = new TableData<FunctionInfoDto>(Draw, list.Count, list.Count, list);

            //await AddTracesInfo(5, 0, "获取菜单列表");

            return Json(PageData);
        }
        public async Task<ActionResult> FunctionAdd(long id)
        {
            var list = await _userApp.GetFunctionInfoListByPidAsync(0, 1);
            if (id == 0)
                return View(new FunctionPage { Id = 0, FullName = "", Url = "", Pid = 0, Status = 0, List = list });
            var dto = await _userApp.GetFunctionInfoByIdAsync(id);
            //await AddTracesInfo(5, 0, "获取菜单信息");
            return View(new FunctionPage { Id = dto.ID, FullName = dto.FullName, Url = dto.URL, Pid = dto.Pid, Status = dto.Status, List = list });
        }

        /// <summary>
        /// 更新菜单信息
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<JsonResult> OperateFunction()
        {
            var dto = new FunctionInfoDto();
            dto.ID = Request.Form["id"].ToInt64();
            dto.FullName = Request.Form["fullName"].ToString();
            dto.URL = Request.Form["url"].ToString();
            dto.Description = Request.Form["des"].ToString();
            dto.Pid = Request.Form["pId"].ToInt64();
            dto.MenuIcon = "";
            dto.Status = Request.Form["status"].ToInt32();
            dto.Code = "";
            bool result;
            string msg;
            try
            {
                if (dto.ID == 0)
                {
                    result = await _userApp.AddFunctionInfoAsync(dto);
                    await AddTracesInfo(2, 0, "新增菜单信息");
                }
                else
                {

                    result = await _userApp.UpdateFunctionInfoAsync(dto);
                    await AddTracesInfo(3, 0, "修改菜单信息");
                }
                msg = result ? "成功" : "失败";
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }
            return CreateJsonGetResult(result, msg);
        }

        public async Task<JsonResult> UpdateStatus()
        {

            var id = Request.Form["id"].ToInt64();
            var status = Request.Form["status"].ToInt32();
            bool result;
            string msg;
            try
            {
                result = await _userApp.UpdateStatusByIdAsync(id, status);
                msg = result ? "成功" : "失败";
            }
            catch (Exception e)
            {
                result = false;
                msg = e.Message;
            }

            await AddTracesInfo(3, 0, "更新菜单信息状态");
            return CreateJsonGetResult(result, msg);
        }

        /// <summary>
        /// 用户管理
        /// </summary>
        /// <returns></returns>
        public async new Task<ActionResult> User()
        {
            //await AddTracesInfo();
            return View();
        }

        /// <summary>
        /// 获取用户信息列表
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> UserList()
        {
            var list = await _userApp.GetUserListAsync(new QueryUserDto());
            var PageData = new TableData<UserInfoDto>(Draw, list.Count, list.Count, list);
            //await AddTracesInfo(5, 0, "获取用户信息列表");
            return Json(PageData);
        }
        /// <summary>
        ///  编辑用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public async Task<ActionResult> UserAdd(long id)
        {
            var list = await _userApp.GetRoleInfoAsync();
            if (id == 0)
            {
                var userPageData0 = new UserPage { UserID = 0, UserName = "", FullName = "", Department = "", JobNumber = "", RoleID = 0, IcCode="", List = list };
                return View(userPageData0);
            }
            var dto = await _userApp.GetUserInfoAsync(id);
            //await AddTracesInfo(5, 0, "获取用户信息");
            var userPageData = new UserPage { UserID = dto.UserID, UserName = dto.UserName, FullName = dto.FullName, Department = dto.Department, JobNumber = dto.JobNumber, RoleID = dto.RoleID,IcCode=dto.IcCode, List = list };

            return View(userPageData);
        }

        public async Task<JsonResult> OperateUser()
        {
            var dto = new UserInfoDto();
            dto.UserID = Request.Form["userID"].ToInt64();
            dto.UserName = Request.Form["userName"].ToString();
            dto.IcCode = Request.Form["icCode"].ToString();
            dto.Password = "123456";
            dto.FullName = Request.Form["fullName"].ToString();
            dto.Department = Request.Form["department"].ToString();
            dto.JobNumber = Request.Form["jobNumber"].ToString();
            dto.RoleID = Request.Form["roleId"].ToInt64();
            bool result;
            var mes = "失败";
            try
            {
                if (dto.UserID == 0)
                {
                    dto.UpdateTime = DateTime.Now;
                    var row = await _userApp.AddUserInfoAsync(dto);

                    await AddTracesInfo(2, 0, "新增用户信息");
                    result = row > 0 ? true : false;
                }
                else
                {
                    result = await _userApp.UpdateUserInfoAsync(dto);
                    await AddTracesInfo(3, 0, "修改用户信息");
                }
                if (result) mes = "成功";


            }
            catch (Exception e)
            {
                result = false;
                mes = e.Message;
            }
            return CreateJsonGetResult(result, mes);
        }
        /// <summary>
        /// 重置用户密码
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> ResetUserPwd()
        {
            var id = Request.Form["id"].ToInt64();
            var pwd = "123456";
            bool result;
            var mes = "失败";
            try
            {
                result = await _userApp.ResetPasswordAsync(id, pwd);
                if (result) mes = "成功";
            }
            catch (Exception e)
            {
                result = false;
                mes = e.Message;
            }
            await AddTracesInfo(3, 0, "重置用户密码");
            return CreateJsonGetResult(result, mes);
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <returns></returns>
        public async Task<JsonResult> DelUser()
        {
            var id = Request.Form["id"].ToInt64();
            bool result;
            var mes = "失败";
            try
            {
                result = await _userApp.DeleteUserInfoAsync(id);
                if (result) mes = "成功";
            }
            catch (Exception e)
            {
                result = false;
                mes = e.Message;
            }
            await AddTracesInfo(4, 0, "删除用户信息");
            return CreateJsonGetResult(result, mes);
        }

    }
}
